/*****************************
 * Copyright (c) 2010 by Co. Ltd.  All rights reserved.
 ****************************/
package com.apache.workday.tools;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang.time.DateFormatUtils;

/**
 * 
 * @{#} DelayCompute.java Create on 2010-9-20 下午07:37:55
 *      <p>
 * </p>
 * @version v 0.1
 */
public class DelayCompute {

	public String getDelayDays(int days, List<String> workDays, String time) {
		if (time == null || "".equals(time)) {
			time = DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:00");
		}
		String time1 = time.substring(0, 10);
		String time2 = time.substring(10);
		String arrt[] = time1.split("-");
		int year = Integer.parseInt(arrt[0]);
		int month = Integer.parseInt(arrt[1]);
		int day = Integer.parseInt(arrt[2]) + 1;
		String dateY = arrt[0];
		String dateM = arrt[1];
		String dateD = arrt[2];
		String timeNew = "";
		int num = 0;
		int count = 0;

		while (true) {
			for (int j = month; j < 13; j++) {
				num = getDayds(month, year) + 1;
				for (int i = day; i < num; i++) {
					if (day < 10) {
						dateD = "0" + day;
					} else {
						dateD = String.valueOf(day);
					}
					if (month < 10) {
						dateM = "0" + month;
					} else {
						dateM = String.valueOf(month);
					}
					timeNew = year + "-" + dateM + "-" + dateD;
					if (!workDays.contains(timeNew)) {
						count++;
					}
					if (count == days) {
						return timeNew + time2;
					}
					day++;
				}
				month++;
				day = 1;
			}
			year++;
			month = 1;
		}
	}

	private int getDayds(int month, int year) {
		int num = 0;
		switch (month) {
		case 1:
			num = 31;
			break;
		case 2:
			num = getDaysOfMonth(year);
			break;
		case 3:
			num = 31;
			break;
		case 4:
			num = 30;
			break;
		case 5:
			num = 31;
			break;
		case 6:
			num = 30;
			break;
		case 7:
			num = 31;
			break;
		case 8:
			num = 31;
			break;
		case 9:
			num = 30;
			break;
		case 10:
			num = 31;
			break;
		case 11:
			num = 30;
			break;
		case 12:
			num = 31;
			break;
		}
		return num;
	}

	/**
	 * 判断闰年
	 * 
	 * @param year  int
	 * @return int
	 */
	private int getDaysOfMonth(int year) {

		int num;
		if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)) {
			num = 29;
		} else {
			num = 28;
		}
		return num;

	}
}
